package com.luoqian.demo02;

public class BallMain {
    public static void main(String[] args) {
        //System.out.println(getInstanceByKey("basketball"));
        System.out.println(getReflectionInstanceByKey("Volleyball"));
        String key = "basketball";
        long start = System.currentTimeMillis();
        for (int i = 0; i <1000000 ; i++) {
            getInstanceByKey(key);// time count: 7
            getReflectionInstanceByKey("Basketball"); // time count:770
                //   慢 调用了native方法
                // 每次newInstance都会做安全许可检查
        }
        long end = System.currentTimeMillis();
        System.out.println("time count:" + (end - start));
    }


    public static Ball getInstanceByKey(String key){
        if ("basketball".equals(key)){
            return new Basketball();
        }
        if ("football".equals(key)){
            return new FootBall();
        }
        return null;
    }

    // 考虑：我们如果向增加一个排球  排球 >>> 实现接口 >>> 重写方法 >>> 更改业务逻辑代码
    // 我们如果向去掉篮球  >>> 更改业务逻辑代码
    // 通过反射来实现
    // 因此 我们获取实例这个fan
    public static Ball getReflectionInstanceByKey(String key){
        String fullPackage = "com.luoqian.demo02";
        Ball ball = null;
        try {
            Class<?> clazz = Class.forName(fullPackage + "." + key);
            ball =  (Ball) clazz.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return ball;
    }


}
